import { computed } from "vue";
import { useRoute } from "vue-router";
import { IMP3Data, useRequestGet } from "./useRequest";

/**
 * 获取MP3导航信息
 * @returns
 */
export function useMP3RouteData() {
	const route = useRoute();
	const key = computed(() => (route.query?.key ?? "") as string);
	const album = computed(() => (route.query?.album ?? "") as string);
	const title = computed(() => (route.query?.title ?? "") as string);
	const artist = computed(() => (route.query?.artist ?? "") as string);
	const priorIndex = computed(() => {
		if (key.value || title.value) {
			return 1;
		} else if (artist.value) {
			return 2;
		} else if (album.value) {
			return 3;
		} else {
			return 0;
		}
	});

	return { key, album, title, artist, priorIndex };
}

/**
 * 获取 MP4 导航信息
 * @returns
 */
export function useMP4RouteData() {
	const route = useRoute();
	const key = computed(() => (route.query?.key ?? "") as string);
	const title = computed(() => (route.query?.title ?? "") as string);
	const priorIndex = computed(() => {
		if (key.value || title.value) {
			return 1;
		} else {
			return 0;
		}
	});

	return { key, title, priorIndex };
}

/**
 * 获取 MP3 整体信息
 */
export function getMP3Info(data: IMP3Data[]) {
	const count = data.length;
	const itemCount = new Set(data.map(({ title }) => title)).size;
	const albumCount = new Set(data.map(({ album }) => album)).size;
	const artistCount = new Set(data.map(({ artist }) => artist)).size;

	return {
		count,
		itemCount,
		albumCount,
		artistCount,
	};
}

/**
 * 强制更新 MP3 数据
 */
export async function forceUpdateMP3() {
	await useRequestGet("media/reset", {}, 25000);
}

/**
 * 请求 MP3 文件数据
 */
export async function decodeMP3(params: Partial<IMP3Data>, timeout = 25000) {
	const res = await useRequestGet("media/decode", params, timeout);

	if (res.data && res.data.code === 404) {
		return null;
	}

	return res?.request?.responseURL;
}

/**
 * 请求 MP3 文件数据
 */
export async function decodeMP3FromRouteData(
	routeData: Partial<ReturnType<typeof useMP3RouteData>>,
	timeout = 25000
) {
	const params = {
		key: routeData!.key!.value,
		title: routeData!.title!.value,
		album: routeData!.album!.value,
		artist: routeData!.artist!.value,
	};

	const res = await useRequestGet("media/decode", params, timeout);

	if (res.data && res.data.code === 404) {
		return null;
	}

	return res?.request?.responseURL;
}

/**
 * 请求 MP4 文件数据
 */
export async function decodeMP4FromRouteData(
	routeData: Partial<ReturnType<typeof useMP3RouteData>>,
	timeout = 25000
) {
	const params = {
		key: routeData!.key!.value,
	};

	const res = await useRequestGet("media/decode", params, timeout);

	if (res.data && res.data.code === 404) {
		return null;
	}

	return res?.request?.responseURL;
}
